#include "date_time.h"

extern RTC_DateTypeDef now_date;
extern RTC_DateTypeDef now_time;

void date_time_init(void)
{
    MX_RTC_Init();

    // if(HAL_RTCEx_BKUPRead(&hrtc,RTC_BKP_DR0)!=0X5050)//是否第一次配置
    // {
    //     HAL_RTCEx_BKUPWrite(&hrtc,RTC_BKP_DR0,0X5050);//标记已经初始化过了
    // }

    date_time_set(&now_date, &now_time);
}

void date_time_set(RTC_DateTypeDef *sDate, RTC_TimeTypeDef *sTime)
{
    if (sTime)
        HAL_RTC_SetTime(&hrtc, sTime, RTC_FORMAT_BIN);

    if (sDate)
        HAL_RTC_SetDate(&hrtc, sDate, RTC_FORMAT_BIN);
}

void date_time_get(RTC_DateTypeDef *sDate, RTC_TimeTypeDef *sTime)
{
    if (sTime)
        HAL_RTC_GetTime(&sTime, sTime, RTC_FORMAT_BIN);

    if (sDate)
        HAL_RTC_GetDate(&hrtc, sDate, RTC_FORMAT_BIN);
}

/******************对time.h的支持***********************/
clock_t clock(void)
{
    return get_ms2();
}

time_t time(time_t *__timer)
{
    time_t ret;
    struct tm info;
    RTC_DateTypeDef sDate;
    RTC_TimeTypeDef sTime;
    HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN);
    HAL_RTC_GetDate(&hrtc, &sDate, RTC_FORMAT_BIN);

    info.tm_year = sDate.Year + 100;
    info.tm_mon = sDate.Month - 1;
    info.tm_mday = sDate.Date;
    info.tm_hour = sTime.Hours;
    info.tm_min = sTime.Minutes;
    info.tm_sec = sTime.Seconds;
    info.tm_isdst = -1;

    ret = mktime(&info);

    if (__timer)
        *__timer = ret;
    return ret;
}
